﻿using System.Collections.Generic;
using System.Linq;

namespace LogManager.Base.Data
{
    public static class FilterExtensions
    {
        public static IQueryable<IEvent> Filter(this IQueryable<IEvent> query,string level = null,string user = null, string type = null)
        {            
            if (!string.IsNullOrEmpty(level))
                query = query.Where(e => e.Level == level);

            if (!string.IsNullOrEmpty(user))
                query = query.Where(e => e.User == user);

            if (!string.IsNullOrEmpty(type))
                query = query.Where(e => e.Type == type);
            
            return query;
        }

        public static IQueryable<IEvent> Filter(this IQueryable<IEvent> query, string serverName = null, string logName = null)
        {
            if (!string.IsNullOrEmpty(serverName))
                query = query.Where(e => e.ServerName == serverName);

            if (!string.IsNullOrEmpty(logName))
                query = query.Where(e => e.LogName == logName);
            
            return query;
        }

        public static IEnumerable<IEvent> All(this IQueryable<IEvent> query)
        {
            var events = new List<IEvent>();

            int counter = 0;
            while (counter <= 30)
            {
                var partialResult = query.Skip(counter * 1024).Take(1024).ToList();
                if (partialResult.Count <= 0)
                    break;
                events.AddRange(partialResult);
                counter++;
            }

            return events;
        }

        public static IQueryable<IEvent> Search(this IQueryable<IEvent> query, string propertyName, string propertySearchValue)
        {
            if (!string.IsNullOrEmpty(propertyName))
                query = query.Where(e => e.Properties.Any(p => p.Key ==propertyName));

            if (!string.IsNullOrEmpty(propertySearchValue))
                query = query.Where(e => e.Properties.Any(p => p.Value == propertySearchValue));

            return query;
        }

    }
}
